﻿using System.IO;
using System.Xml.Serialization;
using System.Text.RegularExpressions;
using ChuanYe.Utils;

namespace System.Data
{
    public static class DataExtension
    {
        public static bool IsNotNULL(this object obj)
        {
            return (DBNull.Value != obj) && obj != null;
        }

        public static short ToShort(this object obj)
        {
            if (obj.IsNotNULL())
            {
                return short.Parse(obj.ToString());
            }
            return 0;
        }
        public static int ToInt(this object obj)
        {
            if (obj.IsNotNULL())
            {
                return int.Parse(obj.ToString());
            }
            return 0;
        }

        public static long ToLong(this object obj)
        {
            if (obj.IsNotNULL())
            {
                return long.Parse(obj.ToString());
            }
            return 0;
        }



        public static Guid ToGUID(this object obj)
        {
            if (obj.IsNotNULL())
            {
                return Guid.Parse(obj.ToString());
            }
            return Guid.Empty;
        }

        public static DateTime ToDateTime(this object obj)
        {
            if (obj.IsNotNULL())
            {
                return DateTime.Parse(obj.ToString());
            }
            return DateTime.Parse("1900-01-01");
        }
        public static decimal ToDecimal(this object obj)
        {
            if (obj.IsNotNULL())
                return decimal.Parse(obj.ToString());
            return 0;
        }






        /// <summary>
        /// 从 实体转化为XML字符串
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="obj">数据</param>
        /// <returns></returns>
        public static string SerializeXML<T>(this object obj)
        {
            try
            {
                MemoryStream stream = new MemoryStream();
                XmlSerializer xml = new XmlSerializer(typeof(T));
                xml.Serialize(stream, obj);
                stream.Position = 0;
                StreamReader sr = new StreamReader(stream);
                string str = sr.ReadToEnd();
                return str;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 从 XML字符串转化为实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T DeserializeXML<T>(this string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(typeof(T));
                    return (T)xmldes.Deserialize(sr);
                }
            }
            catch
            {
                return default(T);
            }
        }
    }
}
